package com.relax.mylock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {
    private boolean isLock = false;

    private Thread isCurrent = null;

    private int lockNum = 0;

    public synchronized void lock() {
        //非第一次进来的时候,还要判断是不是当前线程,如果是当前线程,就不需要等待
        if (isLock && isCurrent != Thread.currentThread()) {
            //不是第一次进来时,要等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //第一次进来的时候
        isLock = true;
        isCurrent = Thread.currentThread();
        lockNum++;

    }

    public synchronized void unlock() {
        if (isCurrent == Thread.currentThread()) {
            lockNum--;
            if (lockNum == 0) {
                //唤醒其他线程,并释放锁
                isLock = false;
                notify();

            }
        }

    }


    public boolean tryLock() {
        return false;
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }


    public Condition newCondition() {
        return null;
    }

    public void lockInterruptibly() throws InterruptedException {

    }

}
